package io.gitee.zhangbinhub.acp.core.file.template

import freemarker.template.Configuration
import io.gitee.zhangbinhub.acp.core.common.CommonTools.getDefaultCharsetName
import io.gitee.zhangbinhub.acp.core.common.log.LogFactory.Companion.getInstance
import io.gitee.zhangbinhub.acp.core.file.FileOperation.buildTemplateDir
import java.io.*

object TemplateService {
    private val log = getInstance(TemplateService::class.java)

    /**
     * 获取模板文件路径
     *
     * @param templateFile 模板文件
     * @return [0]-模板所在文件夹，[1]-模板文件名
     */
    private fun getTemplatePath(templateFile: String): Array<String> {
        return if (templateFile.contains(File.separator)) {
            val fileName = templateFile.substring(templateFile.lastIndexOf(File.separator) + 1)
            val foldPath = templateFile.substring(0, templateFile.lastIndexOf(File.separator))
            arrayOf(foldPath, fileName)
        } else {
            arrayOf(buildTemplateDir(), templateFile)
        }
    }

    /**
     * 通过模板生成文件
     *
     * @param templateFile   模板路径，绝对路径或相对于系统模板根路径
     * @param variables      填充数据集
     * @param resultFilePath 目标文件
     * @return 文件绝对路径
     */
    @JvmStatic
    fun generateFile(templateFile: String, variables: Map<String, Any?>?, resultFilePath: String): String = try {
        val templatePath = getTemplatePath(templateFile)
        val configuration = Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS)
        configuration.defaultEncoding = getDefaultCharsetName()
        configuration.setDirectoryForTemplateLoading(File(templatePath[0]))
        val tp = configuration.getTemplate(templatePath[1])
        val out: Writer = BufferedWriter(OutputStreamWriter(FileOutputStream(resultFilePath)))
        tp.process(variables, out)
        log.info("create file \"" + resultFilePath + "\" from template \"" + templatePath[0] + File.separator + templatePath[1] + "\"")
        resultFilePath
    } catch (e: Exception) {
        log.error(e.message, e)
        ""
    }

    /**
     * 通过模板生成字符串
     *
     * @param templateFile  模板路径，绝对路径或相对于系统模板根路径
     * @param variables     填充数据集
     * @return 目标字符串
     */
    @JvmStatic
    fun generateString(templateFile: String, variables: Map<String, Any?>?): String = try {
        val templatePath = getTemplatePath(templateFile)
        val configuration = Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS)
        configuration.defaultEncoding = getDefaultCharsetName()
        configuration.setDirectoryForTemplateLoading(File(templatePath[0]))
        val tp = configuration.getTemplate(templatePath[1])
        val out: Writer = StringWriter()
        tp.process(variables, out)
        log.info("create string from template \"" + templatePath[0] + File.separator + templatePath[1] + "\"")
        out.toString()
    } catch (e: Exception) {
        log.error(e.message, e)
        ""
    }
}
